package com.devin.service.Impl;

import com.devin.dao.MemberMapper;
import com.devin.dao.MultiMapper;
import com.devin.dao.OrderMapper;
import com.devin.dao.TravellerMapper;
import com.devin.pojo.Member;
import com.devin.pojo.Orders;
import com.devin.pojo.OrdersAndTraveller;
import com.devin.pojo.Traveller;
import com.devin.service.OrdersService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("ordersService")
@Transactional
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private TravellerMapper travellerMapper;
    @Autowired
    private MultiMapper multiMapper;

    @Override
    public List<Orders> findOrders(int page,int size) {
        PageHelper.startPage(page,size);
        List<Orders> ordersList = orderMapper.findOrders();
        return ordersList;
    }

    @Override
    public void addOrder(OrdersAndTraveller ordersAndTraveller) {

        List<Traveller> travellerList = ordersAndTraveller.getTravellerList();
        Orders orders = ordersAndTraveller.getOrders();
        Member member = ordersAndTraveller.getMember();

        /*数据可添加member*/
        memberMapper.addMember(member);
        Integer m = member.getId();

        /*数据库添加orders*/
        orders.setMemberId(m);
        orderMapper.addOrder(orders);


        for(Traveller each:travellerList){
            if(each!=null){
                /*数据库添加traveller*/
                orderMapper.addTravellers(each);
                /*数据库添加order_traveller*/
                orderMapper.addOrderAndTraveller(orders.getId(),each.getId());
            }
        }



    }

    @Override
    public Orders getOrdersInfoById(int orderId) {
        return  orderMapper.getOrdersInfoById(orderId);
    }

    @Override
    public void delOrder(int orderId, int memberId) {


        /*通过中间表查询traveller*/
        List<Traveller> travellerList = travellerMapper.getTravellerById(orderId);

        /*删除中间表*/
        travellerMapper.delOrderAndTraveller(orderId);

        for(Traveller each:travellerList){
            /*删除traveller*/
            travellerMapper.delTraveller(each.getId());
        }
        /*删除订单*/
        orderMapper.delOrder(orderId);

        /*删除member*/
        memberMapper.delMember(memberId);
    }

    /*删除多选的order*/
    @Override
    public void delOrdersChecked(Integer[] ids) {
        multiMapper.delOrdersAndTravellers(ids);
        multiMapper.delOrdersChecked(ids);
    }
}
